/*
 * elementLoader.l
 *
 *  Created on: Apr 21, 2011
 *      Author: mariano
 */

%{
#include "../include/element.h"
#include "../include/array.h"
	
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static Array * magics = NULL;
static Array * elements= NULL;

static Element * outputElement = NULL;


static void parseMagic(){

	int d1, d2;
	char * firstDigit = yytext;
	
	// Get to first digit
	while(*firstDigit == ' ')
		firstDigit++;
		
	// Finish first digit
	char * secondDigit = firstDigit;
	while(*secondDigit != ' ')
		secondDigit++;
	*secondDigit = '\0';
	secondDigit++;	// jump to next character
	
	// Get to second digit
	while(*secondDigit == ' ')
		secondDigit++;
	
	// Finish second digit
	char * termination = secondDigit;
	while(*termination != ',' && *termination != ' ' && *termination != '\0')
		termination++;
	*termination = '\0';
		
	sscanf(firstDigit,"%d", &d1);
	sscanf(secondDigit,"%d", &d2);
	
	d1-= d1 > 0 ? 1 : 0;	// indexes start at 1 on .magic 
	d2-= d2 > 0 ? 1 : 0;	// indexes start at 1 on .magic 
	
	Element * e1 = getElementByIndex(elements, d1);
	Element * e2 = getElementByIndex(elements, d2);
	
	Magic * magic = newMagic(e1,e2,outputElement);
	
	add(magics, magic);

}
	
%}

%s COMBINATION

%option noyywrap

digit [0-9]+

%%

<COMBINATION>[" "]*{digit}[" "]+{digit},/[" "]* {	// There are more magics
	parseMagic();
}


<COMBINATION>[" "]*{digit}[" "]+{digit}/[" "]*[\n]? {	// LAST magic, \n or EOF
	parseMagic();
	BEGIN INITIAL;
}

<COMBINATION>[.\n] { // Nothing, go back to initial
	BEGIN INITIAL;
}

<INITIAL>{digit}:/[" "]* {	
	
	int output = -1;
	sscanf(yytext,"%d:",&output);
	output-= output > 0 ? 1 : 0;	// indexes start at 1 on .magic 
	
	outputElement = getElementByIndex(elements, output);

	BEGIN COMBINATION;
}

<INITIAL>[" "]*\n {} // eat leftovers

. { }

%%

Array * loadMagics(char * filename, Array * elementArray){
	magics = newArray();
	elements = elementArray;
	
	FILE * tmp = yyin;
	yyin = fopen(filename == NULL ? "myelements.magic" : filename, "r");
	if(yyin==NULL){
		return NULL;
	}
	magicLoaderlex();
	yyin = tmp;
	
	Array * out = copyArray(magics);
	deleteArray(magics);
	return out;
}